package com.chefu.carowner.service.impl;

import com.chefu.carowner.config.JwtProperties;
import com.chefu.carowner.pojo.mongo.UserLocation;
import com.chefu.carowner.service.PositionService;
import com.chefu.common.constants.CfConstants;
import com.chefu.common.exception.CfException;
import com.chefu.common.exception.ExceptionEnum;
import com.chefu.common.pojo.R;
import com.chefu.common.utils.CookieUtils;
import com.chefu.common.utils.auth.JwtUtils;
import com.chefu.common.utils.auth.Payload;
import com.chefu.common.utils.auth.UserInfo;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class PositionServiceImpl implements PositionService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private JwtProperties jwtProp;

    @Override
    public void saveLocation(HttpServletRequest request, Double latitude, Double longitude, String addrStr) {
        String token = request.getHeader(CfConstants.APP_TOKEN_HEADER);
        Payload<UserInfo> payload = null;

        try {
            payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), UserInfo.class);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CfException(ExceptionEnum.UNAUTHORIZED);
        }
        UserInfo info = payload.getInfo();
        if (info.getUserType()!=0) throw new CfException(ExceptionEnum.UNAUTHORIZED);
        Long userId = info.getId();

        Query query = new Query(Criteria.where("userId").is(userId));
        if (!mongoTemplate.exists(query, UserLocation.class)){
            UserLocation userLocation = new UserLocation();
            userLocation.setId(ObjectId.get());
            userLocation.setUserId(userId);
            userLocation.setLocation(new GeoJsonPoint(latitude,longitude));
            userLocation.setAddress(addrStr);
            userLocation.setCreateTime(System.currentTimeMillis());
            userLocation.setUpdateTime(System.currentTimeMillis());
            userLocation.setLastUpdateTime(System.currentTimeMillis());
            mongoTemplate.save(userLocation);
        }else{
            Update update = new Update();
            update.set("address",addrStr);
            update.set("updateTime",System.currentTimeMillis());
            update.set("lastUpdateTime",System.currentTimeMillis());
            update.set("location",new GeoJsonPoint(latitude,longitude));
            mongoTemplate.updateFirst(query,update,UserLocation.class);
        }
    }
}
